package com.xyzboom.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Locale;
import java.util.Random;

public class VerifyCode {
    private String code;
    private BufferedImage image;

    public String getCode() {
        return code.toLowerCase(Locale.ROOT);
    }

    public void setCode(String code) {
        this.code = code;
    }

    public BufferedImage getImage() {
        return image;
    }

    public void setImage(BufferedImage image) {
        this.image = image;
    }

    private VerifyCode(String code, BufferedImage image) {
        this.code = code;
        this.image = image;
    }

    public static VerifyCode getVerifyCode() {
        BufferedImage bufferedImage = new BufferedImage(80, 40, BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.getGraphics();
        g.fillRect(0, 0, 80, 40);

        //验证码字符范围
        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
        Random r = new Random();
        int index;
        StringBuilder sb = new StringBuilder(); //保存字符串
        for (int i = 0; i < 4; i++) {
            index = r.nextInt(ch.length);
            g.setColor(getRandomColor());
            Font font = new Font("宋体", Font.BOLD, 20);
            g.setFont(font);
            g.drawString(ch[index] + "", (i * 20) + 2, 23);
            sb.append(ch[index]);
        }

        // 随机添加噪点
        int area = (int) (0.02 * 80 * 40);
        for (int i = 0; i < area; ++i) {
            int x = (int) (Math.random() * 80);
            int y = (int) (Math.random() * 40);
            bufferedImage.setRGB(x, y, (int) (Math.random() * 255));
        }

        // 随机设置验证码中的干扰线
        for (int i = 0; i < 5; i++) {
            //随机获取干扰线的起点和终点
            int x_start = (int) (Math.random() * 80);
            int y_start = (int) (Math.random() * 40);
            int x_end = (int) (Math.random() * 80);
            int y_end = (int) (Math.random() * 40);
            g.setColor(getRandomColor());
            g.drawLine(x_start, y_start, x_end, y_end);
        }
        return new VerifyCode(sb.toString(), bufferedImage);
    }

    private static Color getRandomColor() {
        int r = (int) (Math.random() * 255);
        int g = (int) (Math.random() * 255);
        int b = (int) (Math.random() * 255);
        return new Color(r, g, b);
    }
}
